<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 头部警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>
      <!-- 选择商品分类区 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader
            v-model="SelectedCates"
            :options="CateList"
            :props="cascaderProps"
            @change="handleCateChanged"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isAbled" @click="addOption">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <!-- 操作模板区域 -->
              <!-- eslint-disable-next-line -->
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isAbled" @click="addOption">添加属性</el-button>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <!-- 操作模板区域 -->
              <!-- eslint-disable-next-line -->
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增区域 -->
    <el-dialog
      :title="'添加' + TitleText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="optParamsDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="MsgTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改区域 -->
    <el-dialog :title="'修改' + TitleText" :visible.sync="editParamsDialogVisible" width="50%">
      <!-- 内容主题区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="MsgTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      CateList: [],
      SelectedCates: [],
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      activeName: "many",
      manyTableData: [],
      onlyTableData: [],
      addParamsDialogVisible: false,
      editParamsDialogVisible: false,
      addForm: {
        attr_name: ""
      },
      attrTags:[],
      editForm: {},
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入" + this.MsgTitle,
            trigger: "blur"
          },
          {
            min: 2,
            max: 10,
            message: this.MsgTitle + "的长度在2~10个字符之间",
            trigger: "blur"
          }
        ]
      },
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入" + this.MsgTitle,
            trigger: "blur"
          },
          {
            min: 2,
            max: 10,
            message: this.MsgTitle + "的长度在2~10个字符之间",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.CateList = res.data;
    },
    // 级联选择框变化触发事件
    handleCateChanged() {
      this.getParamsData();

    },
    handleTabClick(tab, event) {
      this.getParamsData();
      console.log(this.activeName);
    },
    async getParamsData() {
      //console.log(this.SelectedCates)
      var len = this.SelectedCates.length;
      // 如果SelectedCates的数组长度不等于3，则表示未选中三级分类
      if (len != 3) {
        this.SelectedCates = [];
        this.manyTableData = []
        this.onlyTableData = []
        return;
      }
      // 选中三级分类
      // 根据所选分类id获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      console.log(res.data)

      res.data.forEach(item=>{
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框中输入的值
        item.inputValue = ''
      })

      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }

      console.log(this.attrTags)
    },
    optParamsDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    async addParams() {
      console.log(this.addForm.attr_name);
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        //可以发起添加用户的网络请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        console.log(res.data);
        this.addParamsDialogVisible = false;
        this.getParamsData();
      });
    },
    addOption() {
      this.addParamsDialogVisible = true;
    },
    // 展示修改面板并获取当前选择数据
    async showEditDialog(val) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${val}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.editForm = res.data;
      console.log(this.editForm);
      this.editParamsDialogVisible = true;
    },
    // 提交修改结果
    async editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        console.log(res.data);
        this.editParamsDialogVisible = false;
        this.getParamsData();
      });
    },
    // 删除事件
    async removeParamsById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => {
        return err;
      });

      console.log(confirmResult);

      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.getParamsData();
    },
    // tag标签点击关闭事件
    handleClose(i,row) {
        row.attr_vals.splice(i,1)
        this.saveAttrVals(row)
    },
    // 点击tag标签中的New Tag 事件
    showInput(row) {
        row.inputVisible = true;
        // $nextTick方法作用就是当页面上的元素被重新渲染后，才会调用回调函数中的代码
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
    //   点击tag标签中的New Tag后 输入内容敲击回车或失去焦点都会触发事件
    handleInputConfirm(row) {   
        let inputValue = row.inputValue;
        if(inputValue.trim().length===0){
            row.inputVisible = false;
            row.inputValue = '';
            return 
        }
    
        row.attr_vals.push(inputValue);
        row.inputVisible = false;
        row.inputValue = '';
        // 发送网络请求，保存这次提交的数据
        this.saveAttrVals(row)
      },
    //   将对attr_vals的操作保存到数据库
    async saveAttrVals(row){
          const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,{ 
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals:row.attr_vals.join(' ')
        }
        );
        if (res.meta.status != 200) {
            return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
      }
  },
  computed: {
    isAbled(){
        if (this.SelectedCates.length === 3) {
            return false
      }
      return true
    },
    // 当前选中的三级分类的ID
    cateId() {
      if (this.SelectedCates.length === 3) {
        return this.SelectedCates[2];
      }
      return null;
    },
    TitleText() {
      if (this.activeName == "many") {
        return "动态参数";
      }
      return "静态属性";
    },
    MsgTitle() {
      if (this.activeName == "many") {
        return "参数名称";
      }
      return "属性名称";
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.el-tag + .el-tag {
    margin-left: 10px;
  }

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>